package com.liang.liangrpceasy.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.liang.liangrpceasy.model.RpcRequest;
import com.liang.liangrpceasy.model.RpcResponse;
import com.liang.liangrpceasy.serializer.JdkSerializer;
import com.liang.liangrpceasy.serializer.Serializer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 服务代理(JDK动态代理)
 */
public class ServiceProxy implements InvocationHandler {

    /**
     * 调用代理
     * @return 结果
     * @throws Throwable 异常
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 指定序列化器
        Serializer serializer = new JdkSerializer();

        // 发请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args)
                .build();

        try {
            byte[] bodyBytes = serializer.serialize(rpcRequest);
            byte[] result;
            try (HttpResponse httpResponse =
                         HttpRequest.post("http://localhost:8081")
                                 .body(bodyBytes)
                                 .execute()) {
                result = httpResponse.bodyBytes();
            }
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
            return rpcResponse.getData();
        } catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
}
